﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;

namespace SoftHelper.Tool
{
    public class COnfigurationHelper
    {

        private static Configuration configuration;

        public static Configuration MyConfiguration
        {
            get
            {
                if (configuration == null)
                {
                    configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                }
                return configuration;
            }
        }


        /// <summary>
        /// 添加配置
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static bool addConfiguration(String key, Object value)
        {
            try
            {
                if (MyConfiguration.AppSettings.Settings[key] != null)
                {
                    MyConfiguration.AppSettings.Settings[key].Value = value.ToString();
                }
                else
                {
                    MyConfiguration.AppSettings.Settings.Add(key, value.ToString());
                }
                MyConfiguration.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }


        /// <summary>
        /// 根据键获取配置文件中的值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static Object getConfigurationValue(String key)
        {
            if (MyConfiguration.AppSettings.Settings[key]!=null)
            {
                return MyConfiguration.AppSettings.Settings[key].Value;
            }
            else
            {
                return String.Empty;
            }
        }


    }
}
